﻿using Azure.Core;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using NetTaste;
using SqlSugar;
using 档案查询系统网络版.Helpers;
using 档案查询系统网络版.Models;

namespace 档案查询系统网络版.Controllers
{
    [Authorize]
    [ApiController]
    [Route("[controller]/[action]")]
    public class AuthController : ControllerBase
    {
        private readonly JwtHelper _jwtHelper;
        private readonly ILogger<AuthController> _logger;
        private readonly ISqlSugarClient _db;

        public AuthController(ILogger<AuthController> logger, JwtHelper jwtHelper, ISqlSugarClient db)
        {
            _logger = logger;
            _jwtHelper = jwtHelper;
            _db = db;
        }

        [AllowAnonymous]
        [HttpPost(Name = "Login")]
        public object Login([FromBody] User request)
        {
            if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
            {
                return BadRequest("用户名或密码不能为空");
            }
            // 查询数据库用户验证
            var auth = _db.Queryable<User>().Where(x => x.Username == request.Username && x.Password == request.Password).First();
            if (auth!= null)
            {
                var token = _jwtHelper.GenerateToken(auth.Id.ToString(), request.Username);
                _logger.LogDebug("登录成功");
                return Ok(new { Token = token });
            }
            return Unauthorized("用户名或密码错误");
        }

        [AllowAnonymous]
        [HttpPost(Name = "Reg")]
        public object Register([FromBody] User request)
        {
            if (string.IsNullOrEmpty(request.Username) || string.IsNullOrEmpty(request.Password))
            {
                return BadRequest("用户名或密码不能为空");
            }
            // 检查用户存在
            if (_db.Queryable<User>().Where(x => x.Username == request.Username).Any())
            {
                return BadRequest("用户名已存在");
            }
            _db.Insertable(request).ExecuteCommand();
            return Ok();
        }
    }
}
